package com.longcai.cm.web.controller;

import com.alibaba.fastjson.JSON;
import com.longcai.cm.base.bean.PageVo;
import com.longcai.cm.bean.CodeMakerBean;
import com.longcai.cm.bean.R;
import com.longcai.cm.common.constant.ConstantValues;
import com.longcai.cm.common.utils.Freemarker;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;

@RestController
@RequestMapping("/sysCodeMaker")
public class SysCodeMakerController {

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 显示数据库所有表信息
     */
    public static final String SHOW_TABLES_MYSQL = "show tables";

    /**
     * 显示数据表对应所有列信息
     */
    public static final String SHOW_COLUMNS_MYSQL = "select  * from Information_schema.columns  where table_Name = '${tablename}' and table_schema='cars_wzpu_cn';  ";


    /**
     * 获取表名列表
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/getTableList")
    public R<List<Map<String, Object>>> getTableList(HttpServletRequest request, HttpServletResponse response) {

        List<Map<String, Object>> a = jdbcTemplate.queryForList(SHOW_TABLES_MYSQL);

        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Map<String, Object> map : a) {
            System.out.println(map);
            for (Entry<String, Object> vo : map.entrySet()) {
                Map<String, Object> mapR = new HashMap<String, Object>();
                mapR.put("tablename", vo.getValue());
                resultList.add(mapR);
            }
        }

        return R.success(resultList);
    }

    /**
     * 根据表名 获取列名 列表
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/getColumnList")
    public R getColumnList(HttpServletRequest request, HttpServletResponse response) {
        String tableNameString = request.getParameter("tablename");
        List<Map<String, Object>> columns = jdbcTemplate.queryForList(SHOW_COLUMNS_MYSQL.replace("${tablename}", tableNameString));
        System.err.println(JSON.toJSONString(columns));
        System.out.println(SHOW_COLUMNS_MYSQL.replace("${tablename}", tableNameString));
        for (Map<String, Object> map : columns) {
            map.put("ELEMENT_TYPE", "0");
            map.put("ISSHOW", "1");
            map.put("ISMUST", "1");
        }

        PageVo<Map<String, Object>> a = new PageVo<>(columns, (int) columns.size());
        return R.success(a);
    }

    /**
     * 下划线格式字符串转换为驼峰格式字符串
     *
     * @param param
     * @return
     */
    public static String underlineToCamel(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        StringBuilder sb = new StringBuilder(param);
        Matcher mc = ConstantValues.COMPILE_WITH_.matcher(param);
        int i = 0;
        while (mc.find()) {
            int position = mc.end() - (i++);
            sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 代码生成器----预览
     *
     * @param request
     * @return
     */
    @RequestMapping("/preview")
    public R<Map<String, Object>> preview(HttpServletRequest request) throws URISyntaxException {

        Map<String, Object> resultPageMap = new HashMap<>();
        // 执行生成方法
        String contextPath = this.getClass().getResource("/").toURI().getPath();
        System.err.println(contextPath);


        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("vo", getBeanByRequest(request));

        String[] tmps = new String[]{"vue.ftl", "api.ftl"};

        for (String string : tmps) {
            String aString = Freemarker.printTemplate(string, dataMap, contextPath);
            resultPageMap.put(string, aString);
        }

        return R.success(resultPageMap);
    }


    /**
     * 从请求中解析---生成实体
     *
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    private CodeMakerBean getBeanByRequest(HttpServletRequest request) {


        // 生成的模块名称
        String moudule = request.getParameter("mouduleName");
        // 生成的模块描述
        String describe = request.getParameter("describe");
        // 传输的配置信息
        String dataString = request.getParameter("data");
        // 表名、实体名
        String tablename = request.getParameter("tablename");

        //数据库字段封装
        List<Object> list = JSON.parseArray(dataString);
        List<Map<String, Object>> columnlist = new ArrayList<Map<String, Object>>();
        for (Object object : list) {
            Map<String, Object> map = (Map<String, Object>) object;
            columnlist.add(map);
        }
        System.err.println(JSON.toJSONString(columnlist));

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("moudule", describe);// 所属父模块
        paramMap.put("describe", describe);// 模块描述

        CodeMakerBean cmb = new CodeMakerBean(tablename, paramMap, columnlist);


        return cmb;
    }


}
